﻿<?php 
class GalleryController extends Controller
{
	public function ActionList($request)
	{
		$this->data['afterworks'] = AfterworkModel::GetAll();	
		$this->View('Empty.php');
	}
	
	public function ActionListImage($request)
	{		
		if (isset($request['id']))
		{
			$this->data['images'] = GalleryModel::GetAllAfterwork($request['id']);
			$this->View('Empty.php');
		}
	}
	
	public function ActionAdd($request)
	{
		$login = LoginModel::GetFromUsername($_SESSION['login']);
		if (count($request) > 0)
		{
			
			$allowedExts = array("gif", "jpeg", "jpg", "png");
			$extension = end(explode(".", $_FILES["file"]["name"]));
			if ((($_FILES["file"]["type"] == "image/gif")
			|| ($_FILES["file"]["type"] == "image/jpeg")
			|| ($_FILES["file"]["type"] == "image/jpg")
			|| ($_FILES["file"]["type"] == "image/pjpeg")
			|| ($_FILES["file"]["type"] == "image/x-png")
			|| ($_FILES["file"]["type"] == "image/png"))
			&& ($_FILES["file"]["size"] < 2000000)
			&& in_array($extension, $allowedExts))
			{
			    if ($_FILES["file"]["error"] > 0)
				{
					echo "Return Code: " . $_FILES["file"]["error"] . "<br>";
				}
			    else
				{
					if (!file_exists("upload/" . $_FILES["file"]["name"]))
					{	
						$path = sha1($_FILES["file"]["name"]).'.'.$extension;
						move_uploaded_file($_FILES["file"]["tmp_name"], $_SERVER['DOCUMENT_ROOT'].'/Content/gallery/'.$path);
						
						$photo = new GalleryModel();
						$photo->path = $path;
						$photo->title = $request['title'];
						$photo->afterwork_id = $request['afterwork_id'];
						$photo->save();
						
						header('Location: /Gallery/List/'); 
					}
				}
			}
			else
			{
				$error = true;
				$this->data['error'] = 'Fichier invalide ou trop gros !';
				$this->View('Error.php');
				return;
			}   
		}
		else
		{
			$this->data['afterworks'] = AfterworkModel::GetAll();	
			$this->View('Empty.php');
		}
	}
}
?>